<?php
namespace addons\TfFutures\handler;

use Yii;
use linslin\yii2\curl;
use addons\TfFutures\common\models\Member;
use addons\TfFutures\common\models\Order;
use addons\TfFutures\services\OrderService;
use addons\TfFutures\common\models\Symbol;
use addons\TfFutures\common\models\SymbolToa;

//SH000001   上证指数
//SZ399001   深证成指
//SH000016   上证50
class Gather {


    public function home(){
        $curl = new curl\Curl();
        $curl = $curl->setHeaders(['Authorization' => 'APPCODE 6225c2c461f644afa3b4ad026c1fe6ba']);
        $resp = $curl->get("http://alirm-com.konpn.com/query/comrms?symbols=SH000001,SH000016,SZ399001");
        if( $curl->errorCode == null )
        {
            $resp = json_decode($resp,true);
            if( !empty($resp['Obj']) ){
                file_put_contents(dirname(dirname(__FILE__)).'/home.json',json_encode($resp['Obj']));
            }
        }
    }

    public function insert($tmpModelList){
        foreach ($tmpModelList as $tmpModel)
        {
            if( !empty($tmpModel['ticekt'])&&$tmpModel['ticekt']['ask']>0&&$tmpModel['ticekt']['bid']>0 ){
            	
                Yii::$app->services->kline->start('rf_addon_tf_futures_symbol',array_merge([
                    'symbol'     => $tmpModel['code'],
                    'digit'      => 4
                ],$tmpModel['ticekt']));

                $this->listen_hold_order($tmpModel['code'],$tmpModel['ticekt']['price'],bcdiv($tmpModel['unit_price'],$tmpModel['unit'],6));
                $this->listen_pending($tmpModel['code'],$tmpModel['ticekt']);
                $this->contract();
            }
        }
        $this->listen_member();
    }

    //杠杆合约过期监听
    protected function contract(){

        $orders = Yii::$app->db->createCommand("SELECT * FROM `rf_addon_tf_futures_member_lever` WHERE `state`='正常'")->queryAll();
        $date = strtotime(date("Y-m-d"));
        foreach ($orders as $k => $v){
            $edate = strtotime($v['edate']);
            if($edate<$date){
                Yii::$app->db->createCommand("UPDATE `rf_addon_tf_futures_member_lever` SET `state`='过期' WHERE `id`={$v['id']}")->execute();
            }
        }


    }
    //持仓订单监听——自动平仓
    protected function listen_hold_order($symbolid,$price,$unit){
        //更新订单所有盈亏
        Yii::$app->db->createCommand(
            "UPDATE `rf_addon_tf_futures_order` SET 
                `profit` = if(`rise_fall`='RISE',{$price} - `open_price`,`open_price` - {$price}) * `volume` * `contract_size` * {$unit}, 
                `close_price` = {$price} 
            WHERE `symbol` = '{$symbolid}' AND `state` = '持仓' AND `status` = 1
        ")->execute();

        //监听所有订单
        $orders = Yii::$app->db->createCommand(
            "SELECT * FROM `rf_addon_tf_futures_order` WHERE `symbol` = '{$symbolid}' AND `state`='持仓' AND `status` = 1 AND 
        `rise_fall`='RISE' AND (
            ( `stop_profit_price` > 0 && {$price} >= `stop_profit_price`) OR
            ( `stop_loss_price`   > 0 && {$price} <= `stop_loss_price`)
        )")->queryAll();
        if (!empty($orders)) {
            foreach ($orders as $order) {
                if( $order['stop_profit_price']>0 && $price >= $order['stop_profit_price'] )
                {
                    OrderService::OrderClose($order['id'],$price,'自动平仓');
                }else if( $order['stop_loss_price']>0 && $price <= $order['stop_loss_price'] )
                {
                    OrderService::OrderClose($order['id'],$price,'自动平仓');
                }
            }
        }

        $orders = Yii::$app->db->createCommand(
            "SELECT * FROM `rf_addon_tf_futures_order` WHERE `symbol` = '{$symbolid}' AND `state`='持仓' AND `status` = 1 AND 
        `rise_fall`='FALL' AND (
            ( `stop_profit_price` > 0 && {$price} <= `stop_profit_price`) OR
            ( `stop_loss_price`   > 0 && {$price} >= `stop_loss_price`)
        )")->queryAll();

        if (!empty($orders)) {
            foreach ($orders as $order) {
                if( $order['stop_profit_price']>0 && $price <= $order['stop_profit_price'] )
                {
                    OrderService::OrderClose($order['id'],$price,'自动平仓');
                }else if( $order['stop_loss_price']>0 && $price >= $order['stop_loss_price'] )
                {
                    OrderService::OrderClose($order['id'],$price,'自动平仓');
                }
            }
        }
    }
    
    private function PendingToPosition($order,$price,$bijiao = 'GT'){
		switch($order['price_type']){
			case 1:
				$price = $price['price'];
				break;
			case 2:
				$price = $price['bid'];
				break;	
			case 3:
				$price = $price['ask'];
				break;	
		}
		if($bijiao == 'GT' && $order['price'] <= $price){
			OrderService::PendingToPosition($order['id']);
		}elseif($bijiao == 'LT' && $order['price'] >= $price){
			OrderService::PendingToPosition($order['id']);
		}
    }
    
    private function CloseOrder($order,$price,$orderss,$bijiao = 'GT'){
    	switch($order['price_type']){
			case 1:
				$price = $price['price'];
				break;
			case 2:
				$price = $price['bid'];
				break;	
			case 3:
				$price = $price['ask'];
				break;	
		}
		if($bijiao == 'GT' && $order['price'] <= $price){
			foreach ($orderss as $k => $value){
				OrderService::OrderClose($value['id'],$price,'自动平仓');
			}
		}elseif($bijiao == 'LT' && $order['price'] >= $price){
			foreach ($orderss as $k => $value){
				OrderService::OrderClose($value['id'],$price,'自动平仓');
			}
		}
    }

    //挂单订单监听
    protected function listen_pending($symbolid,$price){
    	
        $orders = Yii::$app->db->createCommand("SELECT * FROM `rf_addon_tf_futures_order_reason` WHERE `symbol` = '{$symbolid}' AND `state`='挂单' AND `limit`='GT'")->queryAll();
      
        if (!empty($orders)) {
            foreach ($orders as $order){
            	//开仓
            	if($order['type'] == 1){
            		self::PendingToPosition($order,$price);
            	}else{
            		//平仓
            		if($order['rise_fall'] == 'RISE'){
            			$orderss = Order::find()->where(['symbol'=>$order['symbol'],'state'=>'持仓','status'=>1,'member_id'=>$order['member_id'],'rise_fall'=>'RISE'])->asArray()->all();
            		}elseif($order['rise_fall'] == 'FALL'){
            			$orderss = Order::find()->where(['symbol'=>$order['symbol'],'state'=>'持仓','status'=>1,'member_id'=>$order['member_id'],'rise_fall'=>'FALL'])->asArray()->all();
            		}
            		self::CloseOrder($order,$price,$orderss);
            		
            	}
            }
        }
        //设定价格是小于的
        $orders = Yii::$app->db->createCommand("SELECT * FROM `rf_addon_tf_futures_order_reason` WHERE `symbol` = '{$symbolid}' AND `state`='挂单' AND `limit`='LT'")->queryAll();
        if (!empty($orders)) {
            foreach ($orders as $order){
            if($order['type'] == 1){
            		self::PendingToPosition($order,$price,'LT');
            	}else{
            		if($order['rise_fall'] == 'RISE'){
            			$orderss = Order::find()->where(['symbol'=>$order['symbol'],'state'=>'持仓','status'=>1,'member_id'=>$order['member_id'],'rise_fall'=>'RISE'])->asArray()->all();
            		}else{
            			$orderss = Order::find()->where(['symbol'=>$order['symbol'],'state'=>'持仓','status'=>1,'member_id'=>$order['member_id'],'rise_fall'=>'FALL'])->asArray()->all();
            		}
            		self::CloseOrder($order,$price,$orderss,'LT');
            	}
            }
        }
        $orders = Yii::$app->db->createCommand("SELECT * FROM `rf_addon_tf_futures_order_reason` WHERE `state`='挂单' AND `expiration` <= '".date('Y-m-d H:i:s')."'")->queryAll();
        if (!empty($orders)) {
            foreach ($orders as $order){
                Yii::$app->db->createCommand("UPDATE `rf_addon_tf_futures_order_reason` SET `state`='删除' WHERE `id`={$order['id']}")->execute();
            }
        }
    }


    // //用户爆仓监听
    // protected function listen_member(){

    //     //先查询所有用户
    //     $member = Member::find()->asArray()->all();
    //     foreach ($member as $k=>$v) {
    //         $leverids = Order::find()->select('lever_id')->where(['state'=>'持仓','member_id'=>$v['member_id']])->orderBy('lever_id')->asArray()->all();

    //         if (empty($leverids)){
    //             continue;
    //         }
    //         foreach ($leverids as $leverid) {

    //             //获取风险
    //             $userStatic = OrderService::loadStatic($v['member_id'],$v['price'],$leverid['lever_id']);
    //             //获取用户余额

    //             if ($userStatic['riskrate'] < 70){
    //                 //用户风险率小于70%爆仓，先查询所有订单
    //                 $order = Order::find()->where(['member_id'=>$v['member_id'],'lever_id'=>$leverid['lever_id']])->all();
    //                 //循环平仓
    //                 foreach ($order as $key=>$val) {
    //                     OrderService::OrderClose($val->id,null,'强制平仓');
    //                 }
    //             }
    //         }
    //     }
    // }
}